import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // console.log('++++++++++++++++++++++++++')
    // console.log(store.getters.token)
    // debugger
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // debugger
    // debugger
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      // debugger
      Message({
        message: res.message || 'Error0000000000',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      // debugger
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // debugger
      return res
    }
  },
  error => {
    // debugger
    if (error.response.status === 301) {
      Message({
        message: '未登录，请重新登录',
        type: 'error',
        duration: 2 * 1000,
        onClose: function() {
          window.location.href = '/login'
        }
      })
    }
    if (error.response.status === 401) {
      // 说明token过期了,刷新token
      return service.request({
        url: '/admin/refreshtoken',
        method: 'get',
        params: {
          Token: getToken()
        }
      })
        .then(res => {
          debugger
          if (res.data.status === 500) {
            // debugger
            console.error('refreshtoken error => ', res.data.msg)

            // 刷新token失败，神仙也救不了了，跳转到首页重新登录吧
            window.location.href = '/login'
          } else {
            // debugger
            const token = res.data

            // 设置Token
            store.dispatch('user/refreshToken', token)

            debugger
            // 获取当前失败的请求
            const config = error.response.config

            // 重置一下配置
            config.headers['Authorization'] = 'bearer ' + token

            // 清除控制台错误消息
            // console.clear()
            console.log(config)
            // 重试当前请求并返回promise
            return service(config)
          }
        }).catch(res => {
          debugger
          console.error('refreshtoken error =>', res)

          // 刷新token失败，神仙也救不了了，跳转到首页重新登录吧
          window.location.href = '/login'
        })
    }
    if (error.response.status === 403) {
      Message({
        message: '没有后端接口权限',
        type: 'error',
        duration: 2 * 1000,
        onClose: function() {
          window.location.href = '/login'
        }
      })
    }
    return Promise.reject(error)
  }
)

export default service
